﻿using Aribaccio;
using BDPAutodetect.Mgrcore;
using BDPAutodetect.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace BDPAutodetect.Client
{
    /// <summary>
    /// 
    /// </summary>
    public partial class SettingRolePowerViewModel : BaseViewModel<UserControl>
    {
        /// <summary>
        /// 用户管理实例
        /// </summary>
        protected UserManager UserMgr { get; set; }
        /// <summary>
        /// 角色权限管理实例
        /// </summary>
        protected RolePowerManager RolePowerMgr { get; set; }
        /// <summary>
        /// 权限状态信息
        /// </summary>
        [ObservableProperty]
        protected string statusMsg;
        /// <summary>
        /// 当前现在角色项
        /// </summary>
        [ObservableProperty]
        protected MRoleDto? roleItem;
        /// <summary>
        /// 角色数据集
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<MRoleDto> roleItems;
        /// <summary>
        /// 权限树形数据集
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<TreeNode<MPowerPermission>> powerTreeNodes;
        /// <summary>
        /// 角色名称集合
        /// </summary>
        public List<string> RoleNames => this.RoleItems.Count > 0 ? this.RoleItems.Select(p => p.Name).ToList() : new List<string>();

        /// <summary>
        /// 构造函数
        /// </summary>
        public SettingRolePowerViewModel(UserManager argUserManager, RolePowerManager arRrolePowerManager)
        {
            this.StatusMsg = string.Empty;
            this.UserMgr = argUserManager;
            this.RolePowerMgr = arRrolePowerManager;
            this.RoleItems = new ObservableCollection<MRoleDto>();
            this.PowerTreeNodes = new ObservableCollection<TreeNode<MPowerPermission>>();
        }

        /// <summary>
        /// 初始化加载权限编辑
        /// </summary>
        /// <returns></returns>
        protected async Task InitLoadPermission()
        {
            if (this.PowerPermission == null) return;
            var resultTaskPowers = this.UserMgr.GetUserPowers(this.PowerPermission.Power.ID);
            await resultTaskPowers.ConfigureAwait(false);
            if (resultTaskPowers != null && resultTaskPowers.Result != null && resultTaskPowers.Result.Count > 0)
            {
                this.IsVisibilityPermission = Visibility.Visible;
            }
        }

        /// <summary>
        /// 页面初始化加载命令事件
        /// </summary>
        [RelayCommand]
        public async Task ExecuteLoaded()
        {
            if (this.IsLoaded) return;
            //获取编辑权限
            var resultTask = this.InitLoadPermission();
            await resultTask.ConfigureAwait(false);

            //标记初始化加载完成
            this.IsLoaded = true;
            this.IsExecutedIdle = false;
            //初始化查询数据
            resultTask = this.QueryData();
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 新增角色命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteInsert()
        {
            try
            {
                this.IsExecutedIdle = false;
                InputNameDialog dialog = new InputNameDialog(string.Empty, this.RoleNames);
                bool? bResult = dialog.ShowDialog();
                if (!bResult.HasValue || !bResult.Value) return;
                if (string.IsNullOrWhiteSpace(dialog.DialogResultData)) return;

                var result = this.RolePowerMgr.InsertRole(new MRoleDto(0, dialog.DialogResultData));
                await result.ConfigureAwait(false);
                if (result != null && result.Result != null)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        this.RoleItems.Add(result.Result);
                        this.RoleItem = result.Result;
                    }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
                }
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }

        //删除角色命令事件
        [RelayCommand]
        public async Task ExecuteDelete()
        {
            if (this.RoleItem == null) return;
            this.IsExecutedIdle = false;
            try
            {
                var result = this.RolePowerMgr.DeleteRole(this.RoleItem);
                await result.ConfigureAwait(false);
                if (result != null && result.Result)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        this.RoleItems.Remove(this.RoleItem);
                        this.RoleItem = this.RoleItems.First();
                    }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
                }
                else
                {
                    MessageBox.Show("删除失败！", "警告", MessageBoxButton.OK);
                }
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }


        /// <summary>
        /// 编辑角色命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteEditor()
        {
            if (this.RoleItem == null) return;
            try
            {
                this.IsExecutedIdle = false;
                InputNameDialog dialog = new InputNameDialog(this.RoleItem.Name, this.RoleNames);
                bool? bResult = dialog.ShowDialog();
                if (!bResult.HasValue || !bResult.Value) return;
                if (string.IsNullOrWhiteSpace(dialog.DialogResultData)) return;

                var role = this.RoleItem.CloneDeep();
                role.Name = dialog.DialogResultData.Trim();
                var result = this.RolePowerMgr.UpdateRole(role);
                await result.ConfigureAwait(false);
                if (result != null && result.Result)
                {
                    this.RoleItem.Name = dialog.DialogResultData;
                }
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }

        /// <summary>
        /// 保存权限命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteSave()
        {
            if (this.RoleItem == null) return;
            if (this.PowerTreeNodes == null || this.PowerTreeNodes.Count <= 0) return;
            this.IsExecutedIdle = false;
            try
            {
                var resultTask = this.RolePowerMgr.UpdateRolePower(this.PowerTreeNodes.ToList());
                await resultTask.ConfigureAwait(false);
                if (resultTask == null || !resultTask.Result)
                {
                    this.StatusMsg = "部分保存失败";
                    //重新查询数据
                    var resultTaskQuery = this.QueryTrees(this.RoleItem.ID, this.IsVisibilityPermission == Visibility.Visible);
                    await resultTaskQuery.ConfigureAwait(false);
                }
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }

        /// <summary>
        /// 行选择改变命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteSelectedChanged()
        {
            if (this.RoleItem == null) return;
            this.IsExecutedIdle = false;
            bool bIsEnabled = this.IsVisibilityPermission == Visibility.Visible;

            var resultTask = this.QueryTrees(this.RoleItem.ID, bIsEnabled);
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        protected async Task QueryData()
        {
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    this.RoleItems.Clear();
                    var roles = this.RolePowerMgr.GetRoles();
                    if (roles != null && roles.Count > 0)
                    {
                        foreach (var item in roles.OrderBy(v => v.ID))
                        {
                            this.RoleItems.Add(item);
                        }
                        this.RoleItem = this.RoleItems.First();
                    }
                }
                finally
                {
                    this.IsExecutedIdle = true;
                }
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
        }

        /// <summary>
        /// 查询树形节点数据
        /// </summary>
        /// <param name="argRoleID"></param>
        /// <param name="argIsEnabled">是否有权限选择</param>
        /// <returns></returns>
        protected async Task QueryTrees(int argRoleID, bool argIsEnabled)
        {
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    this.PowerTreeNodes.Clear();
                    var treeNodes = this.RolePowerMgr.GetPowerTrees(argRoleID, argIsEnabled, true);
                    if (treeNodes != null && treeNodes.Count > 0)
                    {
                        foreach (var item in treeNodes)
                        {
                            this.PowerTreeNodes.Add(item);
                        }
                    }
                }
                finally
                {
                    this.IsExecutedIdle = true;
                }

            }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
        }
    }
}
